package com.xian.im.modules.command.cmd;

import com.xian.feign.UserChannelClient;
import com.xian.im.common.constant.CommandConstant;
import com.xian.im.common.model.dto.AccountDto;
import com.xian.im.common.model.dto.UserDto;
import com.xian.im.common.model.session.SessionUser;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.proto.MsgResponse;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.modules.command.Command;
import com.xian.im.modules.im.entity.UserEntity;
import com.xian.im.modules.im.service.UserService;
import com.xian.im.modules.security.TokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-01-27 09:26
 **/
@Slf4j
public class LoginHandlerCommand implements Command {

    /**
     * 执行
     *
     * @param request
     * @param ctxId
     */
    @Override
    public void exec(MsgRequest request, String ctxId) {
        UserChannelClient userChannelClient = SpringContextHolder.getBean(UserChannelClient.class);
        log.info("登录消息");
        SessionUser session = userChannelClient.session(ctxId);
        TokenProvider tokenProvider = SpringContextHolder.getBean(TokenProvider.class);
        UserService userService = SpringContextHolder.getBean(UserService.class);
        UserEntity user = userService.getEntityByAccount(session.getAccount());
        UserDto dto = UserDto.builder()
                .id(user.getId())
                .orgId(user.getOrgId())
                .account(user.getAccount())
                .build();
        AccountDto accountDto = new AccountDto();
        accountDto.setChannel(session.getChannel());
        BeanUtils.copyProperties(user,dto);
        dto.setAccountDto(accountDto);
        String token = tokenProvider.createUserToken(dto);
        MsgResponse response = MsgResponse.buildSuccess();
        BeanUtils.copyProperties(request,response);
        response.setBody(token);
        userChannelClient.pushChannelMessage(ctxId,response);
    }

    /**
     * 获取命令
     *
     * @return
     */
    @Override
    public Integer getCmd() {
        return CommandConstant.LOGIN_CMD;
    }
}
